package com.wn.common.net.support

import androidx.lifecycle.LiveData
import com.wn.common.net.model.ApiResponse
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * @Author: wn
 * @Date: 2023/1/10 16:45
 * @Description: 用于将retrofit的返回数据，转化为 liveData 的adapter的工厂类  -- liveData
 */

class LiveDataCallAdapterFactory : CallAdapter.Factory() {
  override fun get(
    returnType: Type,
    annotations: Array<out Annotation>,
    retrofit: Retrofit
  ): CallAdapter<*, *>? {
    // 从类型中提取原始类类型
    if (getRawType(returnType) != LiveData::class.java) return null
    // 可观察到的类型
    val observableType = getParameterUpperBound(0, returnType as ParameterizedType)
    // 原始可观察对象类型
    val rawObservableType = getRawType(observableType)
    if (rawObservableType != ApiResponse::class.java) throw IllegalArgumentException("type must be a resource")
    if (observableType !is ParameterizedType) throw IllegalArgumentException("resource must be a parameterized")

    val responseType = getParameterUpperBound(0, observableType)
    return LiveDataCallAdapter<Any>(responseType)
  }
}